package org.sotower.commons.jdbc.db.adapter;

import java.util.ArrayList;
import java.util.List;

import org.springframework.jdbc.core.SqlParameter;

public class PostgreSQLAdapter extends DBAdapter {
	  public boolean supportsLimit(String sql)
	  {
	    return ((sql != null) && (!(sql.trim().equals(""))));
	  }

	  public String getLimitString(String sql)
	  {
	    if ((sql == null) || (sql.trim().equals(""))) {
	      return sql;
	    }

	    StringBuffer pagingSelect = new StringBuffer(100);
	    pagingSelect.append("SELECT POSTGEL.* FROM ( ");
	    pagingSelect.append(sql);
	    pagingSelect.append(" ) POSTGEL LIMIT  ?  OFFSET  ? ");

	    return pagingSelect.toString();
	  }

	  public List declareLimitParam(List param)
	  {
	    List newparam = null;
	    if (param == null) {
	      newparam = new ArrayList(2);
	      newparam.add(new SqlParameter(4));
	      newparam.add(new SqlParameter(4));
	    } else {
	      newparam = new ArrayList(2 + param.size());
	      newparam.addAll(param);
	      newparam.add(new SqlParameter(4));
	      newparam.add(new SqlParameter(4));
	    }

	    return newparam;
	  }

	  public Object[] setLimitParamValue(Object[] value, int offset, int maxrows)
	  {
	    Object[] newvalue = (Object[])null;

	    if (value == null) {
	      newvalue = new Object[] { new Integer(offset + maxrows), 
	        new Integer(offset) };
	    } else {
	      newvalue = new Object[value.length + 2];
	      System.arraycopy(value, 0, newvalue, 0, value.length);
	      newvalue[(newvalue.length - 2)] = new Integer(offset + maxrows);
	      newvalue[(newvalue.length - 1)] = new Integer(offset);
	    }

	    return newvalue;
	  }

	  public String getTableStructureString()
	  {
	    StringBuffer sb = new StringBuffer();
	    sb.append(" SELECT ");
	    sb.append(" A.ATTNAME AS colname,T.TYPNAME AS type ");
	    sb.append(" FROM PG_CLASS C, PG_ATTRIBUTE A, PG_TYPE T ");
	    sb.append(" WHERE A.ATTNUM > 0");
	    sb.append(" AND A.ATTRELID = C.OID");
	    sb.append(" AND A.ATTTYPID = T.OID");
	    sb.append(" AND C.RELNAME = ?");
	    return sb.toString();
	  }
}
